// pages/playlist-square/playlist-square.js
import request from '../../request/index'
//使用 async await 语法必须引入，固定写法。
import regeneratorRuntime from '../../utils/runtime'
const App = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    threeDList:[],
    playlist:[],
    isMore:true,
    lastTime:null,
    isLoading:false,
    loadingText:"努力加载中..."
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.firstGetPlayList()
  },
  //初始化获取歌单
  async firstGetPlayList() {
    const result = await request({url:"top/playlist/highquality",data:{limit:18}})
    if(result.code !== 200){
      console.log("歌单广场歌单获取失败",result)
      return
    }
    const { playlists, more, lasttime } = result
    let playlist = playlists.map(item => {
      const {name, id, coverImgUrl, playCount} = item
      return {name, id, coverImgUrl, playCount}
    })
    const threeDList = playlist.slice(0,3)
    playlist.splice(0,3)
    this.setData({
      threeDList,
      playlist,
      isMore:more,
      lasTtime:lasttime
    })
  },
  //加载更多歌单
  async loadMorePlaylist() {
    const { lasTtime, playlist } = this.data
    const result = await request({url:"top/playlist/highquality",data:{limit:9,before:lasTtime}})
    if(result.code !== 200){
      console.log("加载更多广场歌单获取失败",result)
      return
    }
    const { playlists, more, lasttime } = result
    const morePlaylist = playlists.map(item => {
      const {name, id, coverImgUrl, playCount} = item
      return {name, id, coverImgUrl, playCount}
    })
    this.setData({
      playlist:[...playlist,...morePlaylist],
      isMore:more,
      lasTtime:lasttime,
      isLoading:false
    })

  },
  

  //去歌单详情页面
  goDetailPlaylist(event) {
    const {id} = event.currentTarget.dataset
    wx.navigateTo({url: '/pages/playlist-detail/playlist-detail?id='+ id})
  },

  //scroll-view滑动到底部
  scrollBottom(event) {
    if(!this.data.isMore){
      this.setData({
        isLoading:true,
        loadingText:"没有更多了..."
      })
      return
    }
    this.setData({isLoading:true},_ => {
      this.loadMorePlaylist()
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})